package com.agentframework.core.annotation;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 扫描并注册带有特定注解的组件
 * 支持以下注解：
 * - @Environment: 环境组件
 * - @Agent: 智能体组件
 * - @Action: 动作组件
 */
public class AgentScannerRegistrar implements ImportBeanDefinitionRegistrar {

    private static final String AGENT_SCAN_ANNOTATION = AgentScan.class.getName();
    private static final String DEFAULT_BASE_PACKAGE = "com.agentframework";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, @NotNull BeanDefinitionRegistry registry) {
        // 1. 解析 @AgentScan 注解
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(AGENT_SCAN_ANNOTATION));
        if (annoAttrs == null) {
            return;
        }

        // 2. 创建扫描器配置器
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(AgentScannerConfigurer.class);

        Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
        if (!BeanNameGenerator.class.equals(generatorClass)) {
            builder.addPropertyValue("nameGenerator", BeanUtils.instantiateClass(generatorClass));
        }

        List<String> basePackages = new ArrayList<>();
        basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("value")).filter(StringUtils::hasText).toList());

        basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("basePackages")).filter(StringUtils::hasText).toList());

        basePackages.addAll(Arrays.stream(annoAttrs.getClassArray("basePackageClasses")).map(ClassUtils::getPackageName).toList());

        if (basePackages.isEmpty()) {
            basePackages.add(getDefaultBasePackage(importingClassMetadata));
            basePackages.add(DEFAULT_BASE_PACKAGE);
        }

        builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(basePackages));

        // 4. 注册扫描器
        registry.registerBeanDefinition(generateBeanName(importingClassMetadata), builder.getBeanDefinition());

    }

    private String generateBeanName(AnnotationMetadata importingClassMetadata) {
        return importingClassMetadata.getClassName() + "#" + AgentScannerRegistrar.class.getSimpleName();
    }

    private static String getDefaultBasePackage(AnnotationMetadata importingClassMetadata) {
        return ClassUtils.getPackageName(importingClassMetadata.getClassName());
    }

}

